package com.dream.api.controller;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dream.base.controller.BaseController;
import com.dream.master.service.ProductCategoryService;
import com.dream.model.master.ProductCategory;
import com.dream.utils.annotation.AccessLog;
import com.dream.utils.annotation.SkipAuthority;
import com.dream.vo.api.ApiResult;
import com.dream.vo.api.ApiSpinnerData;
import com.google.common.collect.Lists;
import com.google.gson.Gson;

/**
 * 
 * @author EvanYu
 *
 */
@Controller
@RequestMapping(value = "/api/mst")
public class ApiMasterController extends BaseController{
	
	@Autowired
	private ProductCategoryService productCategoryService;
	
	@ResponseBody
	@RequestMapping(value = "/cats",produces = "text/json;charset=UTF-8")
	@AccessLog(module="api",content="产品分类")
	@SkipAuthority
	public String category(Model modelMap,HttpServletResponse response) {
		
		ApiResult result = new ApiResult();
		List<ApiSpinnerData> cats = Lists.newArrayList();
		
		ProductCategory childrens = productCategoryService.getChildrens(null);
		if(childrens != null && CollectionUtils.isNotEmpty(childrens.getChildren())){
			for(ProductCategory item : childrens.getChildren()){
				
				//first level
				ApiSpinnerData data = new ApiSpinnerData();
				data.setFrist(item.toSpinnerItem());
				
				ProductCategory subCats = productCategoryService.getChildrens(item.getId());
				if(subCats != null && CollectionUtils.isNotEmpty(subCats.getChildren())){
					for(ProductCategory subItem : subCats.getChildren()){
						data.getSecond().add(subItem.toSpinnerItem());
					}
				}
				cats.add(data);
			}
		}
		result.setMessage(new Gson().toJson(cats));
		return new Gson().toJson(result);
	}
	
}
